package com.example.consult.controller;

import com.example.consult.mapper.RecordMapper;
import com.example.consult.model.ConsultLog;
import com.example.consult.model.UserInfo;
import com.example.consult.service.ConsultService;
import com.example.consult.util.RedisUtil;
import com.example.consult.util.Utils;
import com.example.consult.util.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/Consult")
public class ConsultController {
    HttpSession session ;
    @Autowired
    HttpServletRequest request;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    Utils utils;
    @Autowired
    ConsultService consultService;
    @Autowired
    RecordMapper recordMapper;

    @RequestMapping(value = "send",method = RequestMethod.POST)
    @ResponseBody
    public String sendMessage(@RequestParam String toId,String message){
        session = request.getSession();
        WebSocketServer.sendMessage(toId,message);
        return "ok";
    }

    @RequestMapping(value = "open",method = RequestMethod.POST)
    @ResponseBody
    public String createConnection(){
        session = request.getSession();
        String userId = ((UserInfo)session.getAttribute("User")).getUser_id();
        String to = consultService.getFreeEmployee();
        if (to!=null){
            redisUtil.hset("Employee",to,userId);
            return to;
        }else{
            return "NO FREE";
        }
    }

    @RequestMapping(value="close" ,method = RequestMethod.POST)
    @ResponseBody
    public String createRecord(@RequestParam ConsultLog consultLog){
        session = request.getSession();
        recordMapper.insert(consultLog);
        return "ok";
    }

}
